import streamlit as st
from PIL import Image, ImageFilter, ImageEnhance
import io

@st.cache_data
def process_image(image, crop_params, rotation_angle, filter_option):
    processed_image = image.copy()

    # 裁剪
    if crop_params:
        processed_image = processed_image.crop(crop_params)

    # 旋转
    if rotation_angle:
        processed_image = processed_image.rotate(rotation_angle, expand=True)

    # 滤镜
    if filter_option == "灰度":
        processed_image = processed_image.convert("L")
    elif filter_option == "模糊":
        processed_image = processed_image.filter(ImageFilter.BLUR)
    elif filter_option == "锐化":
        processed_image = processed_image.filter(ImageFilter.SHARPEN)
    elif filter_option == "边缘增强":
        processed_image = processed_image.filter(ImageFilter.EDGE_ENHANCE)

    return processed_image

def main():
    st.title("图像处理应用")

    # 上传图像
    uploaded_file = st.file_uploader("选择一张图片", type=["jpg", "jpeg", "png"])

    if uploaded_file is not None:
        image = Image.open(uploaded_file)
        st.image(image, caption="原始图片", use_column_width=True)

        # 侧边栏控制
        st.sidebar.header("图像处理选项")

        # 裁剪
        st.sidebar.subheader("裁剪")
        crop_left = st.sidebar.number_input("左边界", 0, image.width, 0)
        crop_top = st.sidebar.number_input("上边界", 0, image.height, 0)
        crop_right = st.sidebar.number_input("右边界", 0, image.width, image.width)
        crop_bottom = st.sidebar.number_input("下边界", 0, image.height, image.height)
        crop_params = (crop_left, crop_top, crop_right, crop_bottom)

        # 旋转
        st.sidebar.subheader("旋转")
        rotation_angle = st.sidebar.slider("旋转角度", 0, 360, 0)

        # 滤镜
        st.sidebar.subheader("滤镜")
        filter_option = st.sidebar.selectbox(
            "选择滤镜",
            ("无", "灰度", "模糊", "锐化", "边缘增强")
        )

        # 处理图像
        processed_image = process_image(image, crop_params, rotation_angle, filter_option)

        # 显示处理后的图像
        st.image(processed_image, caption="处理后的图片", use_column_width=True)

        # 下载按钮
        buf = io.BytesIO()
        processed_image.save(buf, format="PNG")
        byte_im = buf.getvalue()
        st.download_button(
            label="下载处理后的图片",
            data=byte_im,
            file_name="processed_image.png",
            mime="image/png"
        )

if __name__ == "__main__":
    main()
